package com.clip.service;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.jml.Email;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import weibo4j.http.AccessToken;

import com.clip.action.util.SessionAttributeKey;
import com.clip.dao.ClipEventDao;
import com.clip.dao.ContactDAO;
import com.clip.dao.NoneuserInterestDAO;
import com.clip.dao.ShareacceptmappingDAO;
import com.clip.dao.UserDAO;
import com.clip.dao.UserEmailDAO;
import com.clip.dao.UserEmailEventDAO;
import com.clip.dao.UserRegInvitesDAO;
import com.clip.dao.UserassinaDAO;
import com.clip.dao.UsermobileinfoDAO;
import com.clip.entity.ClipEvent;
import com.clip.entity.ClipeventPic;
import com.clip.entity.Contact;
import com.clip.entity.EmailSubscribe;
import com.clip.entity.NoneuserClipMapping;
import com.clip.entity.NoneuserInterest;
import com.clip.entity.ShareAcceptmapping;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserEmailEvent;
import com.clip.entity.Userassina;
import com.clip.entity.Usermobileinfo;
import com.clip.entity.csch.City;
import com.clip.entity.csch.District;
import com.clip.entity.csch.Province;
import com.clip.util.ScaleImage;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.clip.util.mail.SimpleMailSender;
import com.opensymphony.xwork2.util.URLUtil;

@Service
@Transactional
public class UserService {
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private UserEmailDAO userEmailDAO;
	@Autowired
	private UserRegInvitesDAO userRegInvitesDAO;
	@Autowired
	private UserEmailEventDAO userEmailEventDAO;
	@Autowired
	private ContactDAO contactDAO;
	@Autowired
	private UserEmailService userEmailService;
	@Autowired
	private ClipEventDao eventDao;
	@Autowired
	private UsermobileinfoDAO usermobileinfoDAO;
	@Autowired
	private UserassinaDAO userassinaDAO;
	@Autowired
	private NoneuserInterestDAO noneuserInterestDAO;
	@Autowired
	private ShareacceptmappingDAO shareacceptmappingDAO;
	
	private final byte[] buffer = new byte[1024*8];
	private ScaleImage scaleImage = new ScaleImage();

	public static int USERSUBSCRIBELENGTH=20;
	public static int USERUNSUBSCRIBELENGTH=6;
	
	public int IMGMAXWIDTH=100;
	public int IMGMAXHEIGHT=100;
	public int SMALLIMGMAXWIDTH=30;
	public int SMALLIMGMAXHEIGHT=30;
	
	public User getUserById(Integer uid){
		User user=userDAO.findById(uid);
		return user;
	}
	public User getUserByEmail(String email){
		User user=null;
		List<User> list = userDAO.findByEmail(email);
		if(list!=null&&list.size()>0){
			user=list.get(0);
		}
		return user;
	}
	public User updateUser(User instance){
		userDAO.attachDirty(instance);
		return instance;
	}
	public void deleteUser(User instance){
		userDAO.delete(instance);
	}
	private void sendWelcomeEmail(User user){
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("name", user.getName());
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"registerWelcome.ftl");
		SimpleMailSender.send(mailcontent,user.getName()+"，你有一个来自档期的消息", user.getEmail());
	}
	/*public String register1(User user,UserRegInvites uri){
		String result = "{result:'注册失败',flag:0}";
		if(user!=null){
			userDAO.save(user);
			UserEmail userEmail = new UserEmail(user.getId(),user.getEmail(),1,1,"注册邮箱",0);
			uri.setStatus(1);
			userEmailDAO.save(userEmail);
			userRegInvitesDAO.update(uri);
			
			result="{result:'您的账号已成功创建',flag:1}";
			//发送欢迎邮件
			sendWelcomeEmail(user);
		}
		return result;
	}*/
	public String activite(String activate){
		String result="{result:'激活失败',flag:0}";
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(activate,4,false);
		if(uel!=null){
			User user = this.userDAO.findById(uel.getUid());
			if(user!=null){
				user.setStatus(1);
				UserEmail userEmail = new UserEmail(user.getId(),user.getEmail(),1,1,"注册邮箱",0);
				userEmailDAO.save(userEmail);
				userDAO.attachDirty(user);
				
				checkAddContacts(user);
				
				result="{result:'激活成功',flag:1}";
				Calendar now=Calendar.getInstance();
				now.clear(Calendar.MILLISECOND);
				now.clear(Calendar.SECOND);
				SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
				
				ClipEvent clipEvent=new ClipEvent();
				clipEvent.setAddress("");
				clipEvent.setAlerttime(0l);
				clipEvent.setBegintime(user.getRegtime());
				clipEvent.setCliptype(1);
				clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册，并于"+dateFormat.format(now.getTime())+" 激活成功。");
				clipEvent.setCreatetime(now.getTimeInMillis());
//				clipEvent.setDeadlinetime(0l);
				Calendar calendar=Calendar.getInstance();
				calendar.setTimeInMillis(now.getTimeInMillis());
				calendar.clear(Calendar.MILLISECOND);
				calendar.clear(Calendar.SECOND);
				calendar.clear(Calendar.MINUTE);
				calendar.set(Calendar.HOUR_OF_DAY,0);
				calendar.add(Calendar.DATE, 1);
				calendar.add(Calendar.MINUTE, -1);
				Long endtime=calendar.getTimeInMillis();
				clipEvent.setIswholeday(1);
				clipEvent.setEndtime(endtime);
				clipEvent.setEventtype(1);
				clipEvent.setIsread(1);
//				clipEvent.setIsvip(0);
				clipEvent.setMobilenotice(0);
//				clipEvent.setProcessstatus(1);
				clipEvent.setReliedclip(0);
				clipEvent.setStatus(1);
				clipEvent.setTitle("注册成功");
				clipEvent.setUid(user.getId());
				clipEvent.setUpdatetime(0l);
				this.eventDao.save(clipEvent);
				ClipEvent memoevent=new ClipEvent();
				memoevent.setBegintime(user.getRegtime());
				memoevent.setTitle("注册成功");
				memoevent.setCliptype(2);
				memoevent.setUid(user.getId());
				memoevent.setCreatetime(now.getTimeInMillis());
				SimpleDateFormat tempdateFormat=new SimpleDateFormat("MMdd");
				Long tmp=Long.parseLong("1"+tempdateFormat.format(now.getTime()));
				memoevent.setEndtime(tmp);
				memoevent.setStatus(1);
				this.eventDao.save(memoevent);
				//发送欢迎邮件
				sendWelcomeEmail(user);
				HttpSession session=Struts2Utils.getSession();
				session.setAttribute(SessionAttributeKey.USER, user);
				this.checkUserLogo(true,session);
			}else{
				result="{result:'激活失败',flag:0}";
			}
			userEmailEventDAO.delete(uel);
		}else{
			result="{result:'无效的链接',flag:0}";
		}
		return result;
	}
	private void checkAddContacts(User user) {
		List<Contact> list=this.contactDAO.findByQuery("from Contact c where c.uid="+user.getId());
		if(list!=null&&list.size()>0){
			for (Contact contact : list) {
				contact.setStatus(1);
				this.contactDAO.attachDirty(contact);
				int otheruid=contact.getContactuid();
				List temp=this.contactDAO.findByQuery("from Contact c where c.uid="+otheruid+" and c.contactuid="+user.getId());
				if(temp!=null&&temp.size()>0){
					Contact c=(Contact) temp.get(0);
					c.setStatus(1);
					this.contactDAO.attachDirty(c);
				}
			}
		}
		
	}
	/**
	 * 用户邀请好友-登陆
	 */
	public String inviteLogin(String code,String emailInput,String pwdInput,String bind,String addftg){
		HttpServletRequest request = ToolsUtils.getRequest();
		String result = "<root>";
		String hql = "";
		User user = null;
		User otherUser = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		if(uel!=null){
			hql = "SELECT u FROM User u WHERE u.email='"+emailInput+"' AND u.pwd='"+ToolsUtils.getStringForMD5(pwdInput)+"' AND u.status=1";
			List<User> userList = this.userDAO.findByQuery(hql);
			user = userList!=null&&userList.size()>0 ? userList.get(0) : null;
			if(user!=null){
				String msg = "";
				otherUser = userDAO.findById(uel.getUid());
				request.getSession().setAttribute(SessionAttributeKey.USER, user);
				this.checkUserLogo(true,request.getSession());
				if(otherUser!=null&&user.getId()!=otherUser.getId()){
					if(addftg.equals("1")){//加好友
						contactDAO.addFriend(user, otherUser, uel.getObj());
					}else{
						contactDAO.unFriend(user, otherUser, uel.getObj());
					}
					msg = "添加好友成功";
				}else{
					msg = "登陆用户与对方用户是同一帐号！添加好友失败";
				}
				if(bind.equals("1")){//绑定
					UserEmail userEmail = new UserEmail(user.getId(),uel.getObj(),0,1,"绑定邮箱",0);
					userEmailService.bindUserEmail(user, userEmail, false);
					msg += "\r\n绑定成功";
				}
				userEmailEventDAO.delete(uel);
				result += "<message>"+msg+"</message>";
			}else{
				result += "<message>帐号或密码错误</message>";
			}
		}else{
			result += "<message>链接无效</message>";
		}
		result += "</root>";
		return result;
	}
	/**
	 * 用户邀请好友-注册
	 * @param code
	 * @param nameInput
	 * @param pwdInput
	 * @param id
	 * @return
	 */
	public String inviteRegister(String code,String emailInput,String nameInput,String pwdInput,String id){
		String result = "<root>";
		User otherUser = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		Date date = new Date();
		if(uel!=null){
			otherUser = userDAO.findById(uel.getUid());
			User user=getUserByEmail(emailInput);
			if(user==null)
				user=new User();
			user.setEmail(emailInput);
			user.setName(nameInput);
			user.setPwd(ToolsUtils.getStringForMD5(pwdInput));
			user.setStatus(0);
			user.setRegtime(date.getTime());
			userDAO.save(user);
			if(user!=null&&otherUser!=null){
				if(id.equals("1")){
					if(emailInput.equals(uel.getObj()))
						contactDAO.addFriend(user, otherUser, uel.getObj());
					else{
						Contact contact=new Contact();
						contact.setUid(user.getId());
						contact.setName(otherUser.getName());
						contact.setPinyinname(ToolsUtils.chinese2pinyin(otherUser.getName()));
						contact.setContactuid(otherUser.getId());
						contact.setContactemail(otherUser.getEmail());
						contact.setContacttypeid(1);
						contact.setStatus(0);
						this.contactDAO.save(contact);
					}
				}else{
					contactDAO.unFriend(user, otherUser,uel.getObj());
				}
				if(!emailInput.equals(uel.getObj())){
					UserEmailEvent ueltemp = new UserEmailEvent(user.getId(),4,date.getTime());
					if(userEmailEventDAO.save(ueltemp)>0){
						String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"register_activate.html?activate="+ueltemp.getCode();
						String title=user.getName()+"，你有一个来自档期的消息";
						Map<String, Object> root = new HashMap<String, Object>();
						root.put("name", user.getName());
						root.put("href", href);
						String mailcontent = com.clip.util.FtlUtils.stringRender(root,"accountActive.ftl");
						SimpleMailSender.send(mailcontent,title, user.getEmail());
						result="<message>您的账号已成功创建,我们会发一封激活邮件给您,请尽快登录邮箱激活</message>";
					}
				}else{
					UserEmail userEmail = new UserEmail(user.getId(),uel.getObj(),1,1,"注册邮箱",0);
					userEmailDAO.save(userEmail);
					user.setStatus(1);
					this.userDAO.attachDirty(user);
					
					Calendar now=Calendar.getInstance();
					now.clear(Calendar.MILLISECOND);
					now.clear(Calendar.SECOND);
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
					
					ClipEvent clipEvent=new ClipEvent();
					clipEvent.setAddress("");
					clipEvent.setAlerttime(0l);
					clipEvent.setBegintime(user.getRegtime());
					clipEvent.setCliptype(1);
					clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册，并激活成功。");
					clipEvent.setCreatetime(now.getTimeInMillis());
//					clipEvent.setDeadlinetime(0l);
					Calendar calendar=Calendar.getInstance();
					calendar.setTimeInMillis(now.getTimeInMillis());
					calendar.clear(Calendar.MILLISECOND);
					calendar.clear(Calendar.SECOND);
					calendar.clear(Calendar.MINUTE);
					calendar.set(Calendar.HOUR_OF_DAY,0);
					calendar.add(Calendar.DATE, 1);
					calendar.add(Calendar.MINUTE, -1);
					Long endtime=calendar.getTimeInMillis();
					clipEvent.setEndtime(endtime);
					clipEvent.setEventtype(1);
					clipEvent.setIsread(1);
//					clipEvent.setIsvip(0);
					clipEvent.setMobilenotice(0);
//					clipEvent.setProcessstatus(1);
					clipEvent.setReliedclip(0);
					clipEvent.setStatus(1);
					clipEvent.setTitle("注册成功");
					clipEvent.setUid(user.getId());
					clipEvent.setUpdatetime(0l);
					this.eventDao.save(clipEvent);
					//发送欢迎邮件
					sendWelcomeEmail(user);
					HttpSession session=Struts2Utils.getSession();
					session.setAttribute(SessionAttributeKey.USER, user);
					this.checkUserLogo(true,session);
				}
				//注册成功
				result += "<message>注册成功,请登录邮箱激活帐号</message>";
			}else{
				//注册失败
				result += "<message>注册失败</message>";
			}
			userEmailEventDAO.delete(uel);
		}else{
			//链接无效
			result += "<message>链接无效</message>";
		}
		result += "</root>";
		return result;
	}
	public String register(String emailInput,String nameInput,String pwdInput,int sex,long birth,String pre_a,String suf_a){
		String result="{result:'该邮箱已被使用',flag:0}";
		if(getUserByEmail(emailInput)==null){
			result="{result:'注册失败',flag:0}";
			User user=new User();
			user.setEmail(emailInput);
			user.setName(nameInput);
			user.setPwd(ToolsUtils.getStringForMD5(pwdInput));
			user.setStatus(0);
			user.setRegtime(new Date().getTime());
			user.setUsertype(1);
			user.setSex(sex);
			if(birth>0l){
				Calendar birthdate=Calendar.getInstance();
				birthdate.setTimeInMillis(birth);
				birthdate.clear(Calendar.MILLISECOND);
				birthdate.clear(Calendar.SECOND);
				birthdate.clear(Calendar.MINUTE);
				birthdate.set(Calendar.HOUR_OF_DAY,0);
				user.setBirth(birthdate.getTimeInMillis());
			}
			if(suf_a!=null&&suf_a.length()>0){
				user.setLiving(pre_a+":"+suf_a);
			}
			userDAO.save(user);
			String temp=sendActivateEmail(user);
			if(temp!=null){
				result=temp;
			}
		}
		return result;
	}
	
	public String sendActivateEmail(User user){
		if(user.getId()>0){
			Date date = new Date();
			UserEmailEvent uel = new UserEmailEvent(user.getId(),4,date.getTime());
			if(userEmailEventDAO.save(uel)>0){
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"register_activate.html?activate="+uel.getCode();
				String title=user.getName()+"，你有一个来自档期的消息";
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", user.getName());
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"accountActive.ftl");
				SimpleMailSender.send(mailcontent,title, user.getEmail());
				return "{result:'您的账号已成功创建,我们会发一封激活邮件给您,请尽快登录邮箱激活.',flag:1}";
			}else
				return null;
		}else
			return null;
	}
	
	public String sendAppActivateEmail(User user,String code){
		if(user.getId()>0){
			Date date = new Date();
//			String code = ToolsUtils.getStringForMD5(user.getId()+date.getTime()+"").substring(0, 10);
//			UserEmailEvent uel = new UserEmailEvent(user.getId(),code,4,date.getTime());
//			if(userEmailEventDAO.save(uel)>0){
				String title="圈友账号激活邮件";
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", user.getName());
				root.put("code", code);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"accountActiveForApp.ftl");
				SimpleMailSender.send(mailcontent,title, user.getEmail());
				return "";
//			}else
//				return null;
		}else
			return null;
	}
	
	/*
	 * 找回密码功能|判断用户是否存在|发送用户邮件
	 */
	public String forgetPwd(String email,String name){
		String result="{result:'邮箱地址与真实姓名不匹配',flag:'0'}";
		User user=getUserByEmail(email);
		if(user!=null&&user.getName().equals(name)){
			Date date = new Date();
			UserEmailEvent uel = new UserEmailEvent(user.getId(),1,date.getTime());
			if(userEmailEventDAO.save(uel)>0){
				String title = name+"，你有一个来自档期的消息";
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"resetpwd.html?activate="+uel.getCode();
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", name);
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"resetPassWord.ftl");
				SimpleMailSender.send(mailcontent,title, user.getEmail());
				result="{result:'信息提交成功,我们会发一封密码找回邮件给您,请尽快登录邮箱处理.',flag:1}";
			}else{
				result="{result:'操作失败',flag:0}";
			}
		}
		return result;
	}
	/*
	 * 密码重置授权
	 */
	public String pwdResetAuthorize(String activate){
		String result="{result:'您的链接无效！',flag:'0'}";
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(activate,1,true);
		if(uel!=null){
			uel.setClick(uel.getClick()+1);
			userEmailEventDAO.update(uel);
			result="{result:'您可以使用密码重置功能修改密码！',flag:'1'}";
		}
		return result;
	}
	/*
	 * 密码重置
	 */
	public String pwdReset(String activate,String pwdInput){
		String result="{result:'您的链接无效！',flag:'0'}";
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(activate,1,true);
		if(uel!=null){
			User user = this.userDAO.findById(uel.getUid());
			if(user!=null){
				user.setPwd(ToolsUtils.getStringForMD5(pwdInput));
				userDAO.attachDirty(user);
			}
			userEmailEventDAO.delete(uel);
			result="{result:'密码修改成功！',flag:'1'}";
		}
		return result;
	}
	/**
	 * @param uid	用户UID
	 * @return	用户所有接受邮箱List<String>
	 */
	public List<String> getUserEmailbyUid(String uid){
		List<String> emailList = new ArrayList<String>();
		String hql="from UserEmail ue where ue.uid="+uid+" and ue.status=1";
		List<UserEmail> userEmailList = userDAO.findByQuery(hql);
		for(UserEmail userEmail : userEmailList){
			emailList.add(userEmail.getEmail());
		}
		return emailList;
	}
	

	
	public List<User> searchUserByName(String nameInput,User currentUser,int usertype) {
		String hql="from User user where user.name like '%"+nameInput+"%' and user.status=1 and user.id<>"+currentUser.getId()+" and user.usertype="+usertype+" order by user.id desc";
		return userDAO.findByQuery(hql);
	}
	public boolean checkHasRelationship(Integer fromuid, Integer touid) {
		List list=this.contactDAO.findByQuery("from Contact c where c.uid="+fromuid+" and c.contactuid="+touid);
		if(list!=null&&list.size()>0)
			return true;
		else
			return false;
	}
	/**
	 * @param emailInput
	 * @param pwdInput
	 * @return 	1: success
	 * 			2: 账号或密码不对
	 * 			3: 账号不是有效邮件地址，无法发送激活邮件
	 * 			4: 账号已被禁止登录
	 */
	public int resendActiveEmail(String emailInput, String pwdInput) {
		User user = getUserByEmail(emailInput);
		if(user!=null&&ToolsUtils.getStringForMD5(pwdInput).equals(user.getPwd())){
			if(user.getStatus()==0){
				this.userEmailEventDAO.executeQuery("delete from UserEmailEvent event where event.uid="+user.getId()+" and event.type=4");
				Date date = new Date();
				UserEmailEvent uel = new UserEmailEvent(user.getId(),4,date.getTime());
				if(Email.parseStr(user.getEmail())!=null){
					if(userEmailEventDAO.save(uel)>0){
						String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"register_activate.html?activate="+uel.getCode();
						String title=user.getName()+"，你有一个来自档期的消息";
						Map<String, Object> root = new HashMap<String, Object>();
						root.put("name", user.getName());
						root.put("href", href);
						String mailcontent = com.clip.util.FtlUtils.stringRender(root,"accountActive.ftl");
						SimpleMailSender.send(mailcontent,title, user.getEmail());
					}
					return 1;
				}else{
					return 3;
				}
			}else if(user.getStatus()==2){
				return 4;
			}else{
				return 1;
			}
		}else{
			return 2;
		}
	}
	public Map updateAvatar(String userID, String imgDada) {
		Map infoMap=new LinkedHashMap();
		User user=this.userDAO.findById(Integer.parseInt(userID));
		if(user!=null&&user.getStatus()==1){
			HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
			String path="";
			
			path=apu.get("apacheAvatarPath");
			
			//采用discuz头像路径产生算法得到头像的后续路径
			String suid=String.format("%09d",Integer.valueOf(userID));
			path+="/"+suid.substring(0, 3)+"/"+suid.substring(3, 5)+"/"+suid.substring(5, 7);
			File bigImg=new File(path+"/"+suid.substring(7, 9)+"_avatar.jpg");
			File smallImg=new File(path+"/"+suid.substring(7, 9)+"_avatar_small.jpg");
			ToolsUtils.strToImg(imgDada, bigImg);//将base64文本转换为图像，并保存入磁盘
			ScaleImage si=new ScaleImage();//图片压缩类
			BufferedImage bufimage=null;
			try {
				bufimage = si.getNewImage(bigImg.getPath(),30,30);
				ToolsUtils.CopyImage(bufimage, smallImg);
			} catch (Exception e) {
				e.printStackTrace();
			}
			infoMap.put("status", "头像修改成功！");
		}else {
			infoMap.put("status", "您没有权限！");
		}
		return infoMap;
	}
	
	public void updateAvatar(int uid, File imgDada) {
		Map infoMap=new LinkedHashMap();
		HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
		String path="";
		
		path=apu.get("apacheAvatarPath");
		
		//采用discuz头像路径产生算法得到头像的后续路径
		String suid=String.format("%09d",uid);
		path+="/"+suid.substring(0, 3)+"/"+suid.substring(3, 5)+"/"+suid.substring(5, 7);
		File bigImg=new File(path+"/"+suid.substring(7, 9)+"_avatar.jpg");
		File smallImg=new File(path+"/"+suid.substring(7, 9)+"_avatar_small.jpg");
		ScaleImage si=new ScaleImage();//图片压缩类
		
		BufferedImage bufimage=null;
		try {
			bufimage = si.getNewImage(imgDada.getPath(),IMGMAXWIDTH,IMGMAXHEIGHT);
			ToolsUtils.CopyImage(bufimage, bigImg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			bufimage = si.getNewImage(imgDada.getPath(),SMALLIMGMAXWIDTH,SMALLIMGMAXHEIGHT);
			ToolsUtils.CopyImage(bufimage, smallImg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void checkUserLogo(boolean isNewUser,HttpSession session){
		String urlbig=null;
		String urlsmall=null;
		if(isNewUser){
			urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"image/clipbig.jpg";
			urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"image/clipsmall.jpg";
		}else{
			User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
			if(currentUser==null)
				return;
			HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
			String path="";
			path=apu.get("apacheAvatarPath");
			String suid=String.format("%09d",Integer.valueOf(currentUser.getId()));
			String secondpath="/"+suid.substring(0, 3)+"/"+suid.substring(3, 5)+"/"+suid.substring(5, 7);;
			path+=secondpath;
			File file=new File(path+"/"+suid.substring(7, 9)+"_avatar.jpg");
			if(file.exists()){
				urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+secondpath+"/"+suid.substring(7, 9)+"_avatar.jpg";
				urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+secondpath+"/"+suid.substring(7, 9)+"_avatar_small.jpg";
			}else{
				urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipbig.jpg";
				urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipsmall.jpg";
			}
		}
		session.setAttribute(SessionAttributeKey.USERLOGO_BIG, urlbig);
		session.setAttribute(SessionAttributeKey.USERLOGO_SMALL, urlsmall);
	}
	
	/**
	 * @param uid
	 * @return 	0 	大头像
	 * 			1	小头像
	 */
	public static List getUserLogoByUid(int uid){
		List<String> urls=new ArrayList<String>();
		if(uid==0){
			String urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipbig.jpg";
			String urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipsmall.jpg";
			urls.add(urlbig);
			urls.add(urlsmall);
		}else{
			String urlbig=null;
			String urlsmall=null;
			HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
			String path="";
			path=apu.get("apacheAvatarPath");
			String suid=String.format("%09d",Integer.valueOf(uid));
			String secondpath="/"+suid.substring(0, 3)+"/"+suid.substring(3, 5)+"/"+suid.substring(5, 7);;
			path+=secondpath;
			File file=new File(path+"/"+suid.substring(7, 9)+"_avatar.jpg");
			if(file.exists()){
				urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+secondpath+"/"+suid.substring(7, 9)+"_avatar.jpg";
				urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+secondpath+"/"+suid.substring(7, 9)+"_avatar_small.jpg";
			}else{
				urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipbig.jpg";
				urlsmall=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipsmall.jpg";
			}
			urls.add(urlbig);
			urls.add(urlsmall);
		}
		return urls;
	}
	/**
	 * @param uid
	 * @param ccuid
	 * @return 	true:表示订阅
	 * 			false:表示未订阅
	 */
	public boolean checkIsSubscribed(int uid, int ccuid) {
		List list=this.contactDAO.findByQuery("select c.id from Contact c where uid="+ccuid+" and contactuid="+uid+" and status=1 and contacttypeid=2");
		if(list!=null&&list.size()>0)
			return true;
		else
			return false;
	}
	
	public long countUserSubscribed(int uid){
		return this.contactDAO.countByQuery("select count(*) from Contact c where c.contacttypeid=2 and c.status=1 and c.contactuid="+uid);
	}
	
	public long countAllsubscribes(){
		return this.userDAO.countByQuery("select count(*) from User user where user.usertype=2 and user.status=1 ");
	}
	
	public List getUserSubscribed(int uid, int currentpage) {
		String query="select u from User u, Contact c where u.usertype=2 and u.status=1 and c.uid=u.id and c.contacttypeid=2 and c.status=1 and c.contactuid="+uid+" order by c.createtime";
		return this.userDAO.pagingByQuery(query,currentpage,UserService.USERSUBSCRIBELENGTH);
	}
	
	public List getUserSubscribed(int uid, int currentpage,int pagelenth) {
		String query="select u from User u, Contact c where u.usertype=2 and u.status=1 and c.uid=u.id and c.contacttypeid=2 and c.status=1 and c.contactuid="+uid+" order by c.createtime";
		return this.userDAO.pagingByQuery(query,currentpage,pagelenth);
	}

	public List getUserAllSubscribed(int uid) {
		String query="select u from User u, Contact c where u.usertype=2 and u.status=1 and c.uid=u.id and c.contacttypeid=2 and c.status=1 and c.contactuid=? order by c.createtime";
		return this.userDAO.findByQuery(query,new Object[]{uid});
	}
	
	public List getAllsubscribes( int currentpage) {
		String query="from User user where user.usertype=2 and user.status=1 order by user.regtime";
		return this.userDAO.pagingByQuery(query,currentpage,UserService.USERUNSUBSCRIBELENGTH);
	}
	public List getRecommendUsersList(int needpagenum,int recommenduserspagelength) {
		String query="select u from User u ,RecommendUser recommend where recommend.uid=u.id order by recommend.priority desc) ";
		return this.userDAO.pagingByQuery(query,needpagenum,recommenduserspagelength);
	}
	public User appReigster(String username, String name,String password,int sex,String birth) {
		if(getUserByEmail(username)==null){
			User user=new User();
			user.setEmail(username);
			user.setName(name);
			user.setPwd(ToolsUtils.getStringForMD5(password));
			user.setStatus(0);
			user.setUsertype(1);
			user.setSex(sex);
			SimpleDateFormat dateFormat=new SimpleDateFormat();
			dateFormat.applyPattern("yyyyMMdd");
			Date obj = null;
			try {
				obj = dateFormat.parse(birth);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(obj!=null)
				user.setBirth(obj.getTime());
			user.setRegtime(new Date().getTime());
			userDAO.save(user);
			return user;
		}else
			return null;
	}
	public boolean checkExistUsername(String username) {
		if(getUserByEmail(username)==null){
			return false;
		}else
			return true;
	}
	public void activateUser(User user) {
		user.setStatus(1);
		user.setUserstatus("");
		this.userDAO.attachDirty(user);
		
		String username=user.getEmail();
		String emailRegex="^([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$";
		Calendar now=Calendar.getInstance();
		if(username.matches(emailRegex)){
			UserEmail userEmail=new UserEmail();
			userEmail.setBindable(1);
			userEmail.setEmail(username);
			userEmail.setStatus(1);
			userEmail.setUid(user.getId());
			userEmail.setContacttypeid(0);
			userEmail.setDescription("注册邮箱");
			this.userEmailDAO.save(userEmail);
		}else{
			Usermobileinfo usermobileinfo=new Usermobileinfo();
			usermobileinfo.setUid(user.getId());
			usermobileinfo.setAddtime(now.getTimeInMillis());
			usermobileinfo.setStatus(1);
			usermobileinfo.setUsername(user.getName());
			usermobileinfo.setMobilenum(user.getEmail());
			this.usermobileinfoDAO.save(usermobileinfo);
		}
		
		now.clear(Calendar.MILLISECOND);
		now.clear(Calendar.SECOND);
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		
		ClipEvent clipEvent=new ClipEvent();
		clipEvent.setAddress("");
		clipEvent.setAlerttime(0l);
		clipEvent.setBegintime(user.getRegtime());
		clipEvent.setCliptype(1);
		clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册，并于"+dateFormat.format(now.getTime())+" 激活成功。");
		clipEvent.setCreatetime(now.getTimeInMillis());
//		clipEvent.setDeadlinetime(0l);
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(now.getTimeInMillis());
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.add(Calendar.DATE, 1);
		calendar.add(Calendar.SECOND, -1);
		Long endtime=calendar.getTimeInMillis();
		clipEvent.setIswholeday(1);
		clipEvent.setEndtime(endtime);
		clipEvent.setEventtype(1);
		clipEvent.setIsread(1);
//		clipEvent.setIsvip(0);
		clipEvent.setMobilenotice(0);
//		clipEvent.setProcessstatus(1);
		clipEvent.setReliedclip(0);
		clipEvent.setStatus(1);
		clipEvent.setTitle("注册成功");
		clipEvent.setUid(user.getId());
		clipEvent.setUpdatetime(0l);
		this.eventDao.save(clipEvent);
		
		ClipEvent memoevent=new ClipEvent();
		memoevent.setBegintime(user.getRegtime());
		memoevent.setTitle("注册成功");
		memoevent.setCliptype(2);
		memoevent.setUid(user.getId());
		memoevent.setCreatetime(now.getTimeInMillis());
		SimpleDateFormat tempdateFormat=new SimpleDateFormat("MMdd");
		Long tmp=Long.parseLong("1"+tempdateFormat.format(now.getTime()));
		memoevent.setEndtime(tmp);
		memoevent.setStatus(1);
		this.eventDao.save(memoevent);
		//发送欢迎邮件
//		sendWelcomeEmail(user);
	}
	/**
	 * for app
	 * @param sinauid
	 * @param accessToken
	 * @param expirein
	 * @param name
	 * @param avatar
	 * @param sex
	 * @param birth
	 * @return
	 */
	public User sinaRegister(String sinauid, String accessToken,long expirein,String name,String avatar,int sex,String birth) {
		//保存用户
		Calendar now=Calendar.getInstance();
		User user=new User();
		user.setEmail("app sina");
		user.setName(name);
		user.setPwd("sina");
		user.setStatus(1);
		user.setUsertype(1);
		user.setRegtime(now.getTimeInMillis());
		user.setIsouter(1);
		user.setSex(sex);
		SimpleDateFormat dateFormat1=new SimpleDateFormat();
		dateFormat1.applyPattern("yyyyMMdd");
		Date obj = null;
		try {
			obj = dateFormat1.parse(birth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(obj!=null)
			user.setBirth(obj.getTime());
		userDAO.save(user);
		//保存新浪授权信息
		Userassina userassina=new Userassina();
		userassina.setUid(user.getId());
		userassina.setSinauid(sinauid);
		userassina.setAccessToken(accessToken);
		userassina.setAccesstime(now.getTimeInMillis());
		userassina.setExpirein(expirein);
		userassinaDAO.save(userassina);
		//保存用户头像
		zoomOutAvatar(user.getId(),avatar);
		
		now.clear(Calendar.MILLISECOND);
		now.clear(Calendar.SECOND);
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		
		ClipEvent clipEvent=new ClipEvent();
		clipEvent.setAddress("");
		clipEvent.setAlerttime(0l);
		clipEvent.setBegintime(user.getRegtime());
		clipEvent.setCliptype(1);
		clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册，并于"+dateFormat.format(now.getTime())+" 激活成功。");
		clipEvent.setCreatetime(now.getTimeInMillis());
//		clipEvent.setDeadlinetime(0l);
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(now.getTimeInMillis());
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.add(Calendar.DATE, 1);
		calendar.add(Calendar.SECOND, -1);
		Long endtime=calendar.getTimeInMillis();
		clipEvent.setIswholeday(1);
		clipEvent.setEndtime(endtime);
		clipEvent.setEventtype(1);
		clipEvent.setIsread(1);
//		clipEvent.setIsvip(0);
		clipEvent.setMobilenotice(0);
//		clipEvent.setProcessstatus(1);
		clipEvent.setReliedclip(0);
		clipEvent.setStatus(1);
		clipEvent.setTitle("注册成功");
		clipEvent.setUid(user.getId());
		clipEvent.setUpdatetime(0l);
		clipEvent.setEventtype(1);
		this.eventDao.save(clipEvent);
		
		
		ClipEvent memoevent=new ClipEvent();
		memoevent.setBegintime(user.getRegtime());
		memoevent.setTitle("注册成功");
		memoevent.setCliptype(2);
		memoevent.setUid(user.getId());
		memoevent.setCreatetime(now.getTimeInMillis());
		SimpleDateFormat tempdateFormat=new SimpleDateFormat("MMdd");
		Long tmp=Long.parseLong("1"+tempdateFormat.format(now.getTime()));
		memoevent.setEndtime(tmp);
		memoevent.setStatus(1);
		this.eventDao.save(memoevent);
		
//		sendWelcomeEmail(user);
		return user;
	}
	
	private void zoomOutAvatar(int uid,String avatar){
		String path=ToolsUtils.getApachePhysicalURL().get("apacheAvatarPath");
		String suid=String.format("%09d",Integer.valueOf(uid));
		path+="/"+suid.substring(0, 3)+"/"+suid.substring(3, 5)+"/"+suid.substring(5, 7);
		File bigImg=new File(path+"/"+suid.substring(7, 9)+"_avatar.jpg");
		File smallImg=new File(path+"/"+suid.substring(7, 9)+"_avatar_small.jpg");
		ScaleImage si=new ScaleImage();//图片压缩类
		BufferedImage bufimage=null;
		try {
			URL url = new URL(avatar);
		    // 打开连接
		    URLConnection con = url.openConnection();
		    // 输入流
		    InputStream is = con.getInputStream();
		    BufferedImage bi = ImageIO.read(is); 
			bufimage = si.imageZoomOut(bi, 100, 100);
			ToolsUtils.CopyImage(bufimage, bigImg);
			bufimage = si.imageZoomOut(bi, 30, 30);
			ToolsUtils.CopyImage(bufimage, smallImg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public User sinaRegister(AccessToken accessTokenObj, String name,String avatar,int sex,long birth,String pre_a,String suf_a) {
		//保存用户
		Calendar now=Calendar.getInstance();
		now.clear(Calendar.MILLISECOND);
		
		User user=new User();
		user.setEmail("sina");
		user.setName(name);
		user.setPwd("sina");
		user.setStatus(1);
		user.setUsertype(1);
		user.setRegtime(new Date().getTime());
		user.setIsouter(1);
		user.setSex(sex);
		if(birth>0l){
			
			Calendar birthdate=Calendar.getInstance();
			birthdate.setTimeInMillis(birth);
			birthdate.clear(Calendar.MILLISECOND);
			birthdate.clear(Calendar.SECOND);
			birthdate.clear(Calendar.MINUTE);
			birthdate.set(Calendar.HOUR_OF_DAY,0);
			user.setBirth(birthdate.getTimeInMillis());
		}
		if(suf_a!=null&&suf_a.length()>0){
			user.setLiving(pre_a+":"+suf_a);
		}
		userDAO.save(user);
		//保存新浪授权信息
		Userassina userassina=new Userassina();
		userassina.setUid(user.getId());
		userassina.setSinauid(accessTokenObj.getUid());
		userassina.setAccessToken(accessTokenObj.getAccessToken());
		userassina.setAccesstime(now.getTimeInMillis());
		userassina.setExpirein(Long.parseLong(accessTokenObj.getExpireIn()));
		userassinaDAO.save(userassina);
		//保存用户头像
		zoomOutAvatar(user.getId(),avatar);
		
		
		now.clear(Calendar.SECOND);
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		
		ClipEvent clipEvent=new ClipEvent();
		clipEvent.setAddress("");
		clipEvent.setAlerttime(0l);
		clipEvent.setBegintime(user.getRegtime());
		clipEvent.setCliptype(1);
		clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册，并于"+dateFormat.format(now.getTime())+" 激活成功。");
		clipEvent.setCreatetime(now.getTimeInMillis());
//		clipEvent.setDeadlinetime(0l);
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(now.getTimeInMillis());
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.add(Calendar.DATE, 1);
		calendar.add(Calendar.SECOND, -1);
		Long endtime=calendar.getTimeInMillis();
		clipEvent.setIswholeday(1);
		clipEvent.setEndtime(endtime);
		clipEvent.setEventtype(1);
		clipEvent.setIsread(1);
//		clipEvent.setIsvip(0);
		clipEvent.setMobilenotice(0);
//		clipEvent.setProcessstatus(1);
		clipEvent.setReliedclip(0);
		clipEvent.setStatus(1);
		clipEvent.setTitle("注册成功");
		clipEvent.setUid(user.getId());
		clipEvent.setUpdatetime(0l);
		clipEvent.setEventtype(1);
		this.eventDao.save(clipEvent);
		
		
		ClipEvent memoevent=new ClipEvent();
		memoevent.setBegintime(user.getRegtime());
		memoevent.setTitle("注册成功");
		memoevent.setCliptype(2);
		memoevent.setUid(user.getId());
		memoevent.setCreatetime(now.getTimeInMillis());
		SimpleDateFormat tempdateFormat=new SimpleDateFormat("MMdd");
		Long tmp=Long.parseLong("1"+tempdateFormat.format(now.getTime()));
		memoevent.setEndtime(tmp);
		memoevent.setStatus(1);
		this.eventDao.save(memoevent);
		
		return user;
	}
	
	public void checkSinaContact(int uid, JSONArray array) {
		for (int i = 0; i < array.size(); i++) {
			JSONObject jsonObject=(JSONObject) array.get(i);
			int sinauid=(Integer)jsonObject.get("sinauid");
			List list=this.userassinaDAO.findByQuery("from Userassina sina where sina.sinauid="+sinauid);
			if(list!=null&&list.size()>0){
				jsonObject.put("isclipuser", false);
				Userassina userassina=(Userassina) list.get(0);
				int someuid=userassina.getUid();
				boolean isrelated=this.checkHasRelationship(uid, someuid);
				jsonObject.put("isfriend", isrelated);
			}else{
				jsonObject.put("isclipuser", false);
			}
		}
	}
	public void updateUserSinatoken(int uid, String accessToken) {
		List list=this.userassinaDAO.findByQuery("from Userassina sina where sina.uid="+uid);
		if(list!=null&&list.size()>0){
			Userassina userassina=(Userassina) list.get(0);
			userassina.setAccessToken(accessToken);
			this.userassinaDAO.attachDirty(userassina);
		}
	}
	public Userassina getUserSinatoken(int uid) {
		List list=this.userassinaDAO.findByQuery("from Userassina sina where sina.uid="+uid);
		if(list!=null&&list.size()>0){
			Userassina userassina=(Userassina) list.get(0);
			return userassina;
		}else
			return null;
	}
	public Userassina getAndUpdateUserassina(String sinauid,AccessToken accessToken) {
		List list=this.userassinaDAO.findByQuery("from Userassina sina where sina.sinauid=?",new Object[]{sinauid});
		if(list!=null&&list.size()>0){
			Calendar now=Calendar.getInstance();
			Userassina userassina=(Userassina) list.get(0);
			if(accessToken!=null){
				userassina.setAccesstime(now.getTimeInMillis());
				userassina.setAccessToken(accessToken.getAccessToken());
				userassina.setExpirein(Long.parseLong(accessToken.getExpireIn()));
				this.userassinaDAO.attachDirty(userassina);
			}
			return userassina;
		}else
			return null;
	}
	public boolean checkUserIsCC(int uid) {
		boolean flag=false;
		String sql="from User u where u.usertype=2 and u.id="+uid;
		List list=this.userDAO.findByQuery(sql);
		if(list!=null&&list.size()>0){
			flag=true;
		}
		return flag;
	}
	
	/**
	 * 用户是否有权限查看这个商家
	 * @param currentUser
	 * @param visitUser
	 * @return
	 */
	public boolean checkIsHaspermission(User currentUser, User visitUser) {
		return true;
	}
	public User submitNoneuserInfo(String nameInput, String emailInput) {
		String sql="from User u where u.email=?";
		List list=this.userDAO.findByQuery(sql, new Object[]{emailInput});
		if(list==null||list.size()<=0){
			User user=new User();
			user.setRegtime(Calendar.getInstance().getTimeInMillis());
			user.setEmail(emailInput);
			user.setName(nameInput);
			user.setUsertype(3);
			user.setStatus(0);
			this.userDAO.save(user);
			//发送详情链接
			return user;
		}else{
			User user=(User) list.get(0);
			if(user.getName().equals(nameInput)){
				return user;
			}else
				return null;
		}
	}
	public boolean checkIsUser(User currentUser) {
		return currentUser!=null&&(currentUser.getStatus()==1||currentUser.getStatus()==0);
	}
	public User changeNoneuserStatus(String email) {
		String sql="from User u where u.usertype=3 and u.email=?";
		List list=this.userDAO.findByQuery(sql,new Object[]{email});
		if(list!=null&&list.size()>0){
			User user=(User) list.get(0);
			if(user.getStatus()==0){
				user.setStatus(1);
				this.userDAO.attachDirty(user);
			}
			return user;
		}else{
			return null;
		}
	}
	public int checkHasbindable(String mobilenum) {
		String query="from Usermobileinfo info where info.status=1 and info.mobilenum='"+mobilenum+"'";
		List list=this.usermobileinfoDAO.findByQuery(query);
		if(list!=null&&list.size()==1){
			Usermobileinfo usermobileinfo=(Usermobileinfo) list.get(0);
			return usermobileinfo.getUid();
		}else{
			return 0;
		}
	}
	public User registerTempUser(String username, String password) {
		User user=new User();
		user.setEmail(username);
		user.setPwd(ToolsUtils.getStringForMD5(password));
		user.setIsouter(0);
		user.setStatus(0);
		user.setUsertype(1);
		this.userDAO.save(user);
		return user; 
	}
	public User appRegisterUpdate(User user, String name, int sex,
			String birth, String mobilenum) {
		Calendar now=Calendar.getInstance();
		user.setSex(sex);
		user.setName(ToolsUtils.htmlEnCode(name));
		SimpleDateFormat dateFormat2=new SimpleDateFormat();
		dateFormat2.applyPattern("yyyyMMdd");
		Date obj = null;
		try {
			obj = dateFormat2.parse(birth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(obj!=null)
			user.setBirth(obj.getTime());
		user.setStatus(1);
		user.setRegtime(now.getTimeInMillis());
		user.setUsertype(1);
		this.userDAO.attachDirty(user);
		Usermobileinfo usermobileinfo=new Usermobileinfo();
		usermobileinfo.setAddtime(now.getTimeInMillis());
		usermobileinfo.setMobilenum(mobilenum);
		usermobileinfo.setStatus(1);
		usermobileinfo.setUid(user.getId());
		usermobileinfo.setUsername(name);
		
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
		
		ClipEvent clipEvent=new ClipEvent();
		clipEvent.setAddress("");
		clipEvent.setAlerttime(0l);
		clipEvent.setBegintime(user.getRegtime());
		clipEvent.setCliptype(1);
		clipEvent.setContent("您于"+dateFormat.format(new Date(user.getRegtime()))+"注册成功。");
		clipEvent.setCreatetime(now.getTimeInMillis());
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(now.getTimeInMillis());
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.add(Calendar.DATE, 1);
		calendar.add(Calendar.MINUTE, -1);
		Long endtime=calendar.getTimeInMillis();
		clipEvent.setIswholeday(1);
		clipEvent.setEndtime(endtime);
		clipEvent.setEventtype(1);
		clipEvent.setIsread(1);
//		clipEvent.setIsvip(0);
		clipEvent.setMobilenotice(0);
//		clipEvent.setProcessstatus(1);
		clipEvent.setReliedclip(0);
		clipEvent.setStatus(1);
		clipEvent.setTitle("注册成功");
		clipEvent.setUid(user.getId());
		clipEvent.setUpdatetime(0l);
		this.eventDao.save(clipEvent);
		ClipEvent memoevent=new ClipEvent();
		memoevent.setBegintime(user.getRegtime());
		memoevent.setTitle("注册成功");
		memoevent.setCliptype(2);
		memoevent.setUid(user.getId());
		memoevent.setCreatetime(now.getTimeInMillis());
		SimpleDateFormat tempdateFormat=new SimpleDateFormat("MMdd");
		Long tmp=Long.parseLong("1"+tempdateFormat.format(now.getTime()));
		memoevent.setEndtime(tmp);
		memoevent.setStatus(1);
		this.eventDao.save(memoevent);
		return user;
	}
	public void submitNoneuserInterest(String emailInput, int eventid) {
		
		ClipEvent clipEvent=this.eventDao.findById(eventid);
		int dealeventid=0;
		if(clipEvent.getSeid()==0){
			dealeventid=clipEvent.getId();
		}else{
			dealeventid=clipEvent.getSeid();
			clipEvent=this.eventDao.findById(dealeventid);
		}
		ShareAcceptmapping acceptmapping2=new ShareAcceptmapping();
		acceptmapping2.setAccepttype(ShareAcceptmapping.INTERESTTYPE);
		acceptmapping2.setEventid(dealeventid);
		acceptmapping2.setUid(0);
		acceptmapping2.setFolloweventid(0);
		acceptmapping2.setOpttime(Calendar.getInstance().getTimeInMillis());
		this.shareacceptmappingDAO.save(acceptmapping2);
		Map<String, Object> root=new HashMap<String, Object>();
		root.put("name", "游客");
		root.put("title", clipEvent.getTitle());

		root.put("url", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?"+clipEvent.getShareid());
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"noneuserclipEmail.ftl");
		SimpleMailSender.send(mailcontent,"你有一个来自档期的消息", emailInput);
		NoneuserInterest noneuserInterest=new NoneuserInterest();
		noneuserInterest.setEmail(emailInput);
		noneuserInterest.setEventid(dealeventid);
		this.noneuserInterestDAO.save(noneuserInterest);
	}
	public boolean checkCCUsername(String preUsername) {
		String sql="from User u where u.email=? and u.usertype=2";
		List list=this.userDAO.findByQuery(sql, new Object[]{preUsername+".clip"});
		if(list==null||list.size()<=0){
			return false;
		}else
			return true;
	}
	public String settle(String usernameInput, String nameInput,String pwdInput, String emailInput, String webSite,
			String preAddress, String sufAddress) {
		String username=usernameInput+".clip";
		if(checkCCUsername(usernameInput)==false){
			User user=new User();
			user.setEmail(username);
			user.setName(nameInput);
			user.setPwd(ToolsUtils.getStringForMD5(pwdInput));
			user.setStatus(0);
			user.setUsertype(2);
			user.setRegtime(new Date().getTime());
			if(webSite!=null&&webSite.length()>0){
				if(webSite.toLowerCase().indexOf("https://")<0||webSite.toLowerCase().indexOf("http://")<0){
					webSite="http://"+webSite;
				}
				if(URLUtil.verifyUrl(webSite))
					user.setBlog(webSite);
			}
			if(sufAddress!=null&&sufAddress.length()>0){
				user.setLiving(preAddress+":"+sufAddress);
			}
			userDAO.save(user);
			UserEmail userEmail=new UserEmail();
			userEmail.setUid(user.getId());
			userEmail.setContacttypeid(1);
			userEmail.setBindable(1);
			userEmail.setEmail(emailInput);
			userEmail.setStatus(1);
			userEmail.setDescription("");
			userEmailDAO.save(userEmail);
			Map<String,Object> root=new HashMap<String, Object>();
			root.put("name", nameInput);
			String title=nameInput+",有一条来自档期的消息";
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"registerApply.ftl");
			SimpleMailSender.send(mailcontent,title, emailInput);
			return null;
		}else{
			return "登录名已被占用";
		}
		
	}
	public User saveDemisionCode(int uid, File ccdemisionfile,String ccdemisionfileFileName) {
		User user=this.userDAO.findById(uid);
		Calendar now=Calendar.getInstance();
		String webPath=null;
		String smallWebPath=null;
		String fname=null;
		if(ccdemisionfile!=null){
			if(ccdemisionfileFileName==null||ccdemisionfileFileName.length()<=0){
				fname=ccdemisionfile.getName();
			}else
				fname=ccdemisionfileFileName;
			try {
				webPath="demension_"+uid+fname.substring(fname.lastIndexOf(".")).toLowerCase();
				String ext=fname.substring(fname.lastIndexOf(".")+1).toLowerCase();;
				String formatname=null;
				if(ext.toUpperCase().equals("JPG")||ext.toUpperCase().equals("JPG")){
					formatname="JPEG";
				}else if(ext.toUpperCase().equals("BMP")){
					formatname="BMP";
				}else if(ext.toUpperCase().equals("PNG")){
					formatname="PNG";
				}
				String dPath=ToolsUtils.getApachePhysicalURL().get("apacheAvatarPath")+"/0/";
				String savePath=dPath+webPath;
				if(!(new File(dPath).exists())){
					new File(dPath).mkdirs();
				}
				int width,height;
				BufferedInputStream bis = null;
				BufferedOutputStream bos = null;
				BufferedImage img = ImageIO.read(ccdemisionfile);
				scaleImage.saveImage(img,savePath, 150,formatname);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		user.setEdu(webPath);
		this.userDAO.attachDirty(user);
		return user;
	}
	
	public String getCCDemensionByUid(int uid){
		if(uid==0){
			String urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/demensioncodedefault.jpg";
			return urlbig;
		}else{
			User user=this.userDAO.findById(uid);
			String urlbig=null;
			if(user==null||user.getUsertype()!=2){
				urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/demensioncodedefault.jpg";
			}else{
				String url=user.getEdu();
				if(url!=null&&url.length()>0){
					HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
					String path="";
					path=apu.get("apacheAvatarPath");
					urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+"/0/"+url;
				}else{
					urlbig=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/demensioncodedefault.jpg";
				}
			}
			return urlbig;
			

		}
		
	}
	
	public static String getRealAddress(String classname,int id){
		if(id==0){
			return null;
		}
		String filepath=null;
		String realaddressname=null;
		if(classname.equals("Province")){
			Province province=new Province();
			filepath=province.getProvinceFilepath();
		}else if(classname.equals("City")){
			City city=new City();
			filepath=city.getCityFilepath();
		}else if(classname.equals("District")){
			District district=new District();
			filepath=district.getDistrictFilepath();
		}
		if(filepath==null){
			return realaddressname;
		}
		SAXBuilder builder=new SAXBuilder(false);
		try {
			Document document=builder.build(filepath);   
			Element es=document.getRootElement();
			List rowlist=es.getChildren("row");
			for(int i=0;i<rowlist.size();i++){
				JSONObject temp=new JSONObject();
				Element element=(Element) rowlist.get(i);
				Integer tempid=Integer.parseInt(element.getChildText("id"));
				if(tempid==id){
					realaddressname=element.getChildText("name");
					break;
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			return realaddressname;
		}
	}

	public Userassina getUserassina(String sinauid) {
		List list=this.userassinaDAO.findByQuery("from Userassina sina where sina.sinauid=?",new Object[]{sinauid});
		if(list!=null&&list.size()<=0){
			return null;
		}else{
			return (Userassina) list.get(0);
		}
	}
	public void updateUserassina(Userassina userassina) {
		this.userassinaDAO.attachDirty(userassina);
	}
	
	public boolean checkIsExistName(String name){
		String sql="from User u where u.name=?";
		List list=this.userDAO.findByQuery(sql, new Object[]{name});
		if(list==null||list.size()<=0){
			return false;
		}else{
			return true;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
		}
	}
	
	public Userassina userBindSina(User currentUser, AccessToken accessToken) {
		Userassina userassina=new Userassina();
		userassina.setAccesstime(Calendar.getInstance().getTimeInMillis());
		userassina.setAccessToken(accessToken.getAccessToken());
		userassina.setExpirein(Long.parseLong(accessToken.getExpireIn()));
		userassina.setSinauid(accessToken.getUid());
		userassina.setUid(currentUser.getId());
		this.userassinaDAO.save(userassina);
		currentUser.setIsouter(1);
		this.userDAO.attachDirty(currentUser);
		return userassina;
	}
	/**
	 * @param currentUser
	 * @param userassina 	in the session
	 */
	public void unbindUserSina(User currentUser, Userassina userassina) {
		if(userassina==null){
			String queryStr="from Userassina u where u.uid=?";
			List list=this.userassinaDAO.findByQuery(queryStr, new Object[]{currentUser.getId()});
			if(list!=null&&list.size()>0){
				Userassina userassina2=(Userassina) list.get(0);
				this.userassinaDAO.delete(userassina2);
			}
		}else{
			this.userassinaDAO.delete(userassina);
		}
		currentUser.setIsouter(0);
		this.userDAO.attachDirty(currentUser);
		
	}

}
